import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:provide/provide.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/http/apis/live.dart';
import 'package:qgchat/http/models/LiveListModel.dart';
import 'package:qgchat/states/states_model/user.dart';
import 'package:qgchat/widgets/Zego/ZegoFace.dart';
import 'package:qgchat/widgets/Zego/ZegoPreview.dart';
import 'package:zego_express_engine/zego_express_engine.dart';
import 'package:zego_faceunity_plugin/zego_faceunity_plugin.dart';

import 'Bloc/LiveRoomInfoBloc.dart';

class LiveRoom extends StatefulWidget {
  final int id;
  LiveRoom(this.id, {Key key}) : super(key: key);

  @override
  _LiveRoomState createState() => _LiveRoomState();
}

class _LiveRoomState extends State<LiveRoom> {
  @override
  void dispose() {
    LiveApis.liveClose(widget.id);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider<LiveRoomInfoBlocBloc>(
      create: (context) => LiveRoomInfoBlocBloc(widget.id),
      child: WillPopScope(
        onWillPop: () async => false,
        child: _ZegoInit(
          child: Scaffold(
            backgroundColor: Colors.grey,
            body: Stack(
              children: [
                ZegoPreviewBox(),
                _UserInfo(),
                _ToolPanel(),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

// 即构初始化
class _ZegoInit extends StatefulWidget {
  final Widget child;
  _ZegoInit({@required this.child, Key key}) : super(key: key);

  @override
  __ZegoInitState createState() => __ZegoInitState();
}

class __ZegoInitState extends State<_ZegoInit> {
  String roomID;

  @override
  void initState() {
    super.initState();

    // 前置摄像头
    ZegoExpressEngine.instance.useFrontCamera(true);
    // 默认开启摄像头
    ZegoExpressEngine.instance.enableCamera(true);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();

    final user = Provide.value<UserState>(context).info;
    if (user?.id == null) return;
    final liveId = context.bloc<LiveRoomInfoBlocBloc>().id;
    roomID = 'live-$liveId';

    // 创建用户对象
    ZegoUser uid = ZegoUser.id('${user.id}');
    // 开始登陆房间
    ZegoExpressEngine.instance.loginRoom(roomID, uid);
    // 开始推流
    ZegoExpressEngine.instance.startPublishingStream('${user.id}');
  }

  @override
  void dispose() {
    // 开启摄像头
    ZegoExpressEngine.instance.enableCamera(true);
    // 停止推流
    ZegoExpressEngine.instance.stopPublishingStream();
    // 登出房间
    ZegoExpressEngine.instance.logoutRoom(roomID);

    super.dispose();
  }

  @override
  Widget build(BuildContext context) => widget.child;
}

// 主播信息
class _UserInfo extends StatelessWidget {
  const _UserInfo({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final top = MediaQuery.of(context).padding.top;
    return BlocBuilder<LiveRoomInfoBlocBloc, LiveListModel>(
      builder: (context, state) {
        if (state.id == null) return Container();

        return Positioned(
          top: top + px(30),
          left: px(30),
          child: Container(
            height: px(60),
            decoration: BoxDecoration(
              color: Colors.black.withOpacity(.3),
              borderRadius: BorderRadius.circular(px(30)),
            ),
            child: Stack(
              overflow: Overflow.visible,
              alignment: Alignment.centerLeft,
              children: [
                Row(
                  children: [
                    Container(
                      margin: EdgeInsets.only(left: px(90)),
                      padding: EdgeInsets.only(right: px(30)),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            state.memberNickname,
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: px(26),
                            ),
                          ),
                          Text(
                            "id: ${state.aid}",
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: px(20),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
                Positioned(
                  left: 0,
                  child: Container(
                    width: px(70),
                    height: px(70),
                    padding: EdgeInsets.all(px(3)),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(px(35)),
                    ),
                    child: CircleAvatar(
                      backgroundImage: NetworkImage(state.memberHead),
                    ),
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }
}

// 工具栏
class _ToolPanel extends StatefulWidget {
  _ToolPanel({Key key}) : super(key: key);

  @override
  __ToolPanelState createState() => __ToolPanelState();
}

class __ToolPanelState extends State<_ToolPanel> {
  // 当前是否前置摄像头
  bool isFront = true;

  @override
  Widget build(BuildContext context) {
    return Positioned(
      bottom: px(150),
      right: px(30),
      child: Column(
        children: [
          Container(
            width: px(84),
            padding: EdgeInsets.symmetric(vertical: px(44)),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(px(42)),
              color: Colors.black.withOpacity(.3),
            ),
            child: Column(
              children: [
                GestureDetector(
                  onTap: () {
                    ZegoFace.instance.show(context);
                  },
                  child: _ToolPanelBtn(
                    icon: 'beauty',
                    text: '美颜',
                  ),
                ),
                SizedBox(height: px(44)),
                GestureDetector(
                  onTap: () {
                    isFront = !isFront;
                    ZegoFaceunityPlugin.instance.switchCamera(isFront
                        ? ZegoCameraPosition.Front
                        : ZegoCameraPosition.Back);
                  },
                  child: _ToolPanelBtn(
                    icon: 'change_camera',
                    text: '切换',
                  ),
                ),
              ],
            ),
          ),
          SizedBox(height: px(30)),
          GestureDetector(
            onTap: () {
              // 关闭页面
              Navigator.pop(context);
            },
            child: Container(
              width: px(70),
              height: px(70),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(px(35)),
                color: Colors.black.withOpacity(.3),
              ),
              child: Icon(
                Icons.close,
                color: Colors.white,
              ),
            ),
          ),
        ],
      ),
    );
  }
}

// 可操作工具栏
class _ToolPanelBtn extends StatelessWidget {
  final String icon;
  final String text;
  const _ToolPanelBtn({
    @required this.icon,
    @required this.text,
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      child: Column(
        children: [
          Image.asset(
            "assets/images/icon/$icon.png",
            width: px(40),
            height: px(40),
            fit: BoxFit.contain,
          ),
          SizedBox(height: px(7)),
          Text(
            text,
            style: TextStyle(
              color: Colors.white,
              fontSize: px(20),
            ),
          ),
        ],
      ),
    );
  }
}
